package cn.tedu.baking.controller;

import cn.tedu.baking.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/")
@Slf4j
public class UploadController {
    @Value("${filePath}")
    private String dirPath;

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //得到上传图片原始名称
        String fileName = file.getOriginalFilename();
        log.info("上传图片原始名称:"+fileName);
        //得到文件后缀.jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一的文件名, UUID.randomUUID()得到的唯一标识
        fileName = UUID.randomUUID()+suffix;
        log.info("上传图片名称:"+fileName);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        //得到相关日期的路径
        String dataPath = simpleDateFormat.format(new Date());
        //创建文件对象
        File dirFile = new File(dirPath+dataPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();//创建
        }
        //把图片保存到指定路径
        file.transferTo(new File(dirPath+dataPath+fileName));
        //上传成功后 把图片路径响应给客户端
        return JsonResult.ok(dataPath+fileName);
    }

    @PostMapping("remove")
    public JsonResult remove(String url){
        log.info("删除图片路径:"+url);
        //删除路径对应磁盘中的文件
        new File(dirPath+url).delete();
        return JsonResult.ok();
    }
}
